class EventEmitter {
  constructor () {
    this.events = {}
  }
  on (name,fn) {
    if (this.events[name] == undefined) {
      this.events[name] = []
    }
    this.events[name].push(fn)
  }
  emit (name, ...args) {
    const fns = this.events[name]
    if (fns.length > 0) {
      fns.forEach(fn=>{
        fn.apply(this, args)
      })
    }
  }
  off (name, fn) {
    // const fns = this.events[name]
    // const index = fns.indexOf(fn)
    // if (index > -1) {
    //   fns.splice(index, 1)
    // }
    if (!this.events[name]) return
    this.events[name] = this.events[name].filter(item=>{
      return item !== fn
    })
  }
  once (name, fn) {
    const onceFn = function () {
      fn.call(this, arguments)
      this.off(name, onceFn)
    }
    this.on(name, onceFn)
  }
  clear(name){
    this.events[name] = []
  }
}

// 防抖
function debounce (fn, delay) {
  let timer = null
  return function () {
    if (timer) clearTimeout(timer)
    timer = setTimeout(()=>{
      fn.call(this, arguments)
    },delay)
  }
}

// 节流
function throttle (fn, delay) {
  let timer = null
  return function () {
    if (timer) return
    timer = setTimeout(()=>{
      fn()
    },delay)
  }
}

// 手写 将虚拟dom转换为真实dom

const VDOM = {
  tag: 'DIV',
  attrs: {
    id: 'app'
  },
  children: [
    {
      tag: 'SPAN',
      children: [
        {
          tag: 'A',
          children: []
        }
      ]
    },
    {
      tag: 'SPAN',
      children: [
        {
          tag: 'A',
          children: []
        },
        {
          tag: 'A',
          children: []
        }
      ]
    }
  ]
}

function transferDom (VDomObject) {
  const {tag, attrs, children} = VDomObject
  let parent = document.createElement(tag.toLowerCase())
  if (attrs) {
    for(let key in attrs) {
      parent.setAttribute(key, attrs[key])
    }
  }
  if (children && children.length > 0) {
    children.forEach(child=>{
      parent.append(transferDom(child))
    })
  }
  return parent
}
console.log(transferDom(VDOM))